<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出报表"
    :width="600"
    @close="handleClose"
  >
    <el-form
      ref="exportFormRef"
      :model="exportForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="报表类型" prop="report_type">
        <el-select
          v-model="exportForm.report_type"
          placeholder="请选择报表类型"
          style="width: 100%"
          @change="handleReportTypeChange"
        >
          <el-option label="资产报表" value="asset" />
          <el-option label="任务报表" value="task" />
          <el-option label="风险报表" value="risk" />
          <el-option label="部门报表" value="department" />
          <el-option label="责任人报表" value="person" />
        </el-select>
      </el-form-item>

      <el-form-item label="导出格式" prop="format">
        <el-select
          v-model="exportForm.format"
          placeholder="请选择导出格式"
          style="width: 100%"
        >
          <el-option label="Excel (.xlsx)" value="xlsx" />
          <el-option label="CSV (.csv)" value="csv" />
          <el-option label="PDF (.pdf)" value="pdf" />
        </el-select>
      </el-form-item>

      <el-form-item label="报表模板" prop="template">
        <el-select
          v-model="exportForm.template"
          placeholder="请选择报表模板"
          style="width: 100%"
          :loading="templatesLoading"
          @focus="loadTemplates"
        >
          <el-option
            v-for="template in availableTemplates"
            :key="template.id"
            :label="template.name"
            :value="template.id"
          >
            <div>
              <div>{{ template.name }}</div>
              <div style="font-size: 12px; color: #909399">
                {{ template.description }}
              </div>
            </div>
          </el-option>
        </el-select>
        <div class="form-tip">选择模板将使用预设的报表格式和字段</div>
      </el-form-item>

      <el-form-item label="包含内容">
        <el-checkbox-group v-model="includeOptions">
          <el-checkbox label="charts">包含图表</el-checkbox>
          <el-checkbox label="trends">包含趋势数据</el-checkbox>
          <el-checkbox label="comparison">包含对比数据</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="报表语言" prop="language">
        <el-select
          v-model="exportForm.language"
          placeholder="请选择语言"
          style="width: 100%"
        >
          <el-option label="简体中文" value="zh-CN" />
          <el-option label="English" value="en-US" />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="exportForm.report_type === 'department'"
        label="指定部门"
      >
        <el-select
          v-model="exportForm.department_ids"
          placeholder="请选择部门（留空则导出所有部门）"
          multiple
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.name"
            :value="dept.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="自定义字段" v-if="false">
        <el-select
          v-model="exportForm.custom_fields"
          placeholder="请选择要包含的字段"
          multiple
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="field in customFields"
            :key="field.value"
            :label="field.label"
            :value="field.value"
          />
        </el-select>
        <div class="form-tip">选择要包含在报表中的自定义字段</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :loading="exporting"
        @click="handleConfirmExport"
      >
        确认导出
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElLoading, type FormInstance } from "element-plus";
import { exportReport, getReportTemplates } from "../../../servers";
import type { FormRules } from "element-plus";

const props = defineProps<{
  modelValue: boolean;
  currentReportType?: string;
  timeRange?: string;
  dateRange?: [Date, Date] | null;
  departments?: Array<{ id: number; name: string }>;
  departmentOptions?: Array<{ label: string; value: string }>;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "export-success"): void;
}>();

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const exportFormRef = ref<FormInstance>();
const exporting = ref(false);
const templatesLoading = ref(false);
const availableTemplates = ref<any[]>([]);

// 导出表单
const exportForm = reactive({
  report_type: props.currentReportType || "department",
  format: "xlsx" as "xlsx" | "csv" | "pdf",
  template: "",
  language: "zh-CN",
  department_ids: [] as number[],
  custom_fields: [] as string[],
});

// 包含选项
const includeOptions = ref<string[]>(["charts"]);

// 部门列表（优先使用 departmentOptions，如果没有则使用 departments）
const departments = computed(() => {
  if (props.departmentOptions && props.departmentOptions.length > 0) {
    return props.departmentOptions.map((dept) => ({
      id: dept.value,
      name: dept.label,
    }));
  }
  return props.departments || [];
});

// 自定义字段选项（根据报表类型动态生成）
const customFields = computed(() => {
  const fieldsMap: Record<string, Array<{ label: string; value: string }>> = {
    asset: [
      { label: "部门名称", value: "department_name" },
      { label: "处理率", value: "processing_rate" },
      { label: "平均处理时间", value: "avg_processing_time" },
    ],
    department: [
      { label: "部门名称", value: "department_name" },
      { label: "总资产", value: "total_assets" },
      { label: "处理率", value: "processing_rate" },
    ],
    task: [
      { label: "任务名称", value: "task_name" },
      { label: "执行状态", value: "status" },
      { label: "成功率", value: "success_rate" },
    ],
    risk: [
      { label: "风险等级", value: "risk_level" },
      { label: "风险分数", value: "risk_score" },
      { label: "处理状态", value: "processing_status" },
    ],
    person: [
      { label: "责任人", value: "responsible_person" },
      { label: "处理率", value: "processing_rate" },
      { label: "综合评分", value: "overall_score" },
    ],
  };
  return fieldsMap[exportForm.report_type] || [];
});

// 表单验证规则
const rules = reactive<FormRules>({
  report_type: [
    { required: true, message: "请选择报表类型", trigger: "change" },
  ],
  format: [{ required: true, message: "请选择导出格式", trigger: "change" }],
  language: [{ required: true, message: "请选择报表语言", trigger: "change" }],
});

// 格式化日期
const formatDate = (date: Date) => {
  return `${date.getFullYear()}-${(date.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
};

// 加载报表模板
const loadTemplates = async () => {
  if (availableTemplates.value.length > 0) return;

  templatesLoading.value = true;
  try {
    const result = await getReportTemplates({
      report_type: exportForm.report_type as any,
      language: exportForm.language,
    });

    if (result.data && result.data.templates) {
      availableTemplates.value = result.data.templates;

      // 如果当前模板不在列表中，清空选择
      if (
        exportForm.template &&
        !availableTemplates.value.find((t) => t.id === exportForm.template)
      ) {
        exportForm.template = "";
      }
    }
  } catch (error: any) {
    console.error("加载报表模板失败:", error);
    // 不显示错误提示，因为模板是可选的
  } finally {
    templatesLoading.value = false;
  }
};

// 报表类型变化时重新加载模板
const handleReportTypeChange = () => {
  exportForm.template = "";
  availableTemplates.value = [];
  loadTemplates();
};

// 确认导出
const handleConfirmExport = async () => {
  if (!exportFormRef.value) return;

  try {
    await exportFormRef.value.validate();
  } catch {
    return;
  }

  exporting.value = true;
  const loading = ElLoading.service({ text: "正在导出报表，请稍候..." });

  try {
    // 构建导出参数
    const params: any = {
      report_type: exportForm.report_type,
      format: exportForm.format,
      language: exportForm.language,
      include_charts: includeOptions.value.includes("charts"),
      include_trends: includeOptions.value.includes("trends"),
      include_comparison: includeOptions.value.includes("comparison"),
      time_range: props.timeRange === "custom" ? "custom" : props.timeRange,
    };

    // 添加时间范围
    if (props.timeRange === "custom" && props.dateRange) {
      params.start_date = formatDate(props.dateRange[0]);
      params.end_date = formatDate(props.dateRange[1]);
    }

    // 添加模板（如果选择了）
    if (exportForm.template) {
      params.template = exportForm.template;
    }

    // 添加部门ID（如果选择了）
    if (exportForm.department_ids && exportForm.department_ids.length > 0) {
      params.department_ids = exportForm.department_ids;
    }

    // 添加自定义字段（如果选择了）
    if (exportForm.custom_fields && exportForm.custom_fields.length > 0) {
      params.custom_fields = exportForm.custom_fields;
    }

    const result = await exportReport(params);

    if (result.data) {
      // 处理文件下载
      const downloadUrl = result.data.data.download_url;
      const fileName = result.data.data.file_name;

      if (downloadUrl) {
        // 如果返回的是 URL，直接下载
        // 判断是否是完整 URL 还是相对路径
        if (
          downloadUrl.startsWith("http://") ||
          downloadUrl.startsWith("https://")
        ) {
          // 完整 URL，直接使用
          window.open(downloadUrl, "_blank");
        } else {
          // 相对路径，需要拼接基础 URL
          const baseUrl = import.meta.env.VITE_API_URL || "";
          const fullUrl = downloadUrl.startsWith("/")
            ? `${baseUrl}${downloadUrl}`
            : `${baseUrl}/${downloadUrl}`;
          console.log(fullUrl, "fullUrl");
          // return;
          const a = document.createElement("a");
          a.href = fullUrl;
          a.download = fileName || "report";
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }

        ElMessage.success("报表导出成功，文件下载已开始");
        emit("export-success");
        handleClose();
      } else {
        // 如果返回的是文件数据，可能需要其他处理方式
        ElMessage.warning("导出成功，但未获取到下载链接");
      }
    }
  } catch (error: any) {
    console.error("导出报表失败:", error);
    ElMessage.error(error?.message || "报表导出失败，请稍后重试");
  } finally {
    exporting.value = false;
    loading.close();
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  // 重置表单
  if (exportFormRef.value) {
    exportFormRef.value.resetFields();
  }
  exportForm.report_type = props.currentReportType || "department";
  exportForm.format = "xlsx";
  exportForm.template = "";
  exportForm.language = "zh-CN";
  exportForm.department_ids = [];
  exportForm.custom_fields = [];
  includeOptions.value = ["charts"];
  availableTemplates.value = [];
};

// 监听弹窗打开，初始化数据
watch(
  () => props.modelValue,
  (visible) => {
    if (visible) {
      exportForm.report_type = props.currentReportType || "department";
      // 延迟加载模板，避免不必要的请求
      setTimeout(() => {
        loadTemplates();
      }, 100);
    }
  }
);

// 监听报表类型变化
watch(
  () => props.currentReportType,
  (newType) => {
    if (newType) {
      exportForm.report_type = newType;
    }
  }
);
</script>

<style scoped lang="scss">
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.5;
}
</style>
